﻿/************************************
//提交作业模块
************************************/

Ext.namespace('EHSubmit.Work.Submit');

Ext.namespace('EHSubmit.Work.Submit.ObjectiveItem');

// 加载客观题
function loadObjectiveItems(){
	var goalId = EHSubmit.Work.Submit.CurrentGoalId;
	
	var form = Ext.getCmp('ObjectiveSubmitForm');
	form.removeAll(true);
	
	Ext.Ajax.request({
		url: EHSubmit.ajaxRoot + 'QuestionHandler.ashx',
		params: {
			Op: 'listQes',
			goalID: goalId
		},
		success: function(response, opts) {
			var jsonObj = Ext.decode(response.responseText);
			var success = jsonObj.success;

			if(success){
				//获取服务器端的数据(解析后返回的是对象)
				
				var data = Ext.decode(response.responseText).data;
				
				for (var i=0;i<data.length;i++){
					form.add(new Ext.ux.Question({qType:data[i].Type, order:i+1, qTitle:data[i].Content, qId: data[i].QID, qBody:data[i].Options}));
					
				}
				//窗体重新布局
				form.doLayout();
			}
			else{
				alert('error');	
			}
			
			
		}
	});
}
EHSubmit.Work.Submit.ObjectiveItem.SubmitForm ={
	xtype:'form',
	id:'ObjectiveSubmitForm',
	padding:5,
	width:468,
	autoScroll:true,
	border:false,
	bodyStyle: 'background-color:#DFE8F6',
	layout:'form',
	autoHeight:true
}

// 客观题窗体
EHSubmit.Work.Submit.ObjectiveItem.WinConfig ={
	id: 'objectiveItemSubmitWin',
	xtype: 'window',
	width: 500,
	height: 600,
	//plain: true,
	border: true,
	autoScroll:true,
	layout: 'fit',
	modal: true,
	title: '提交作业(客观题)',
	frame: true,
	layout:'form',
	listeners:{
		activate: loadObjectiveItems    // 每次激活窗体时刷新题目
	},
	items: [
		EHSubmit.Work.Submit.ObjectiveItem.SubmitForm
	],
	buttons:[
		{
			text:'提交',
			handler: function(){
				//给填空的input绑定事件来验证
				var isBlankValid = true;
				var i = 0;
				var blankAnsInput = Ext.select('li.x-question-blank input').elements;
				while(blankAnsInput[i]){
					var blankAns = blankAnsInput[i].value.trim();
					var blankAnsRe = /^[\u4E00-\u9FA5 | \w | '.' ]+['%']?([','][\u4E00-\u9FA5 | \w | '.' ]+['%']?)*$/;   //暂不支持含括号的处理
					if(blankAns != ''){
						isBlankValid = blankAnsRe.test(blankAns);
						
						//----格式不对则提示要求修改-----
						if(!isBlankValid){
							Ext.Msg.show({
							   title:'提示',
							   msg: '填空题答案格式不正确,请修改!',
							   buttons: Ext.Msg.OK,
							   icon: Ext.MessageBox.WARNING
							});
							
							return;
						}
					}
					
					i++;
				}
				
				Ext.MessageBox.confirm('确定','提交这后就不能再更改，您确定要提交吗？',function(btn){
					if(!btn || btn == 'no')
						return;
						
					var frm = Ext.getCmp('ObjectiveSubmitForm');
					frm.getForm().submit({     // 提交
						url: EHSubmit.ajaxRoot + 'AnswerHandler.ashx',
						params:{
							Op:'addObjectiveWork',
							goalId:EHSubmit.Work.Submit.CurrentGoalId,
							goalName:EHSubmit.Work.Submit.CurrentGoalName
						},
						waitTitle: '等待',
						waitMsg: '正在上传，请稍后...',
						method: 'POST',
						success: function(form, action) {
							var successed = action.result.success;
							var msg = action.result.msg;
							if (successed) {
								///////////////  提交成功处理  ///////////////////
								Ext.MessageBox.alert('提示', msg);
								
								//删除列表项
								EHSubmit.Work.Submit.ChooseForm.DataStore.remove(EHSubmit.Work.Submit.ChooseForm.DataStore.getById(EHSubmit.Work.Submit.CurrentGoalId));
								
								//关闭窗体
								EHSubmit.closeWin(EHSubmit.Work.Submit.ObjectiveItem.WinConfig);
								//////////////////////////////////////////////////
							}
							else {
								Ext.MessageBox.alert('失败', '信息：' + action.result.msg);
							}
						},
						failure: function(form, action) {
							var errmsg = action.result.msg;
							Ext.MessageBox.alert('错误', errmsg);
						}   // failure  
					});												
				});
				
				
				
			}// ----handler
		},{
			text:'取消',
			handler:function(){
				EHSubmit.closeWin(EHSubmit.Work.Submit.ObjectiveItem.WinConfig);
			}
		}	 
	]
	
};

//////////////////////////////////////////////////////////////////////
//// 选择要提交的作业窗体
Ext.namespace('EHSubmit.Work.Submit.ChooseForm');

//列模式
EHSubmit.Work.Submit.ChooseForm.ColumnModel = new Ext.grid.ColumnModel([
    { header: '作业ID', sortable: true, hidden: true, dataIndex: 'ID' },
    { header: '作业名', width: 400, sortable: true, hidden: false, dataIndex: 'Title' },
	{ header: '类型', width:80,sortable:true, hidden:false, renderer:EHSubmit.Format.goalTypeRenderer , dataIndex:'GoalType' },
    { header: '布置时间', width: 200, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'PublishTime' },
    { header: '最后期限', width: 200, sortable: true, renderer: Ext.util.Format.dateRenderer('Y年m月d日'), dataIndex: 'DeadLine' },
    { header: '附件', width: 60, sortable: false, renderer: EHSubmit.Format.goalAttachRenderer, dataIndex: 'AttachPath' },
    { header: '说明', sortable: false, dataIndex: 'Description' }
]);


// 数据源
EHSubmit.Work.Submit.ChooseForm.DataStore = new Ext.data.Store({
    baseParams: { Op: 'listGoals', sid: '20' },      // 需要传递操作参数  sid学生的ID
    proxy: new Ext.data.HttpProxy({ url: EHSubmit.ajaxRoot + 'UploadHandler.ashx' }),  //后台具体处理
    reader: new Ext.data.JsonReader({
            totalProperty: 'count',    //总记录个数
            root: 'data',
            id: 'ID'
        },
        [   // 数据模型
            { name: 'ID' },
            { name: 'Title' },
			{ name: 'GoalType' },
            { name: 'PublishTime'},
            { name: 'DeadLine' },
            { name: 'AttachPath' },
            { name: 'Description' },
			{ name: 'GoalType' }
    ]),
    listeners: {
        /// 加载异常处理
        exception: function(proxy, type, action, options, response){
            Ext.MessageBox.alert('数据加载错误!','请与管理员联系');
            
        }
    }
});

EHSubmit.Work.Submit.ChooseForm.GridPanel = {
    xtype: 'grid',
    title: '选择作业',
    id: 'Submit_ChooseGrid',
    frame: true,
    border: true,
//    autoHeight: true,       // 自动调整高度
    height: 540,
    loadMask: true,         // 加载数据时遮住
    ds: EHSubmit.Work.Submit.ChooseForm.DataStore,
    cm: EHSubmit.Work.Submit.ChooseForm.ColumnModel,
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true              // 一次只选一个
    }),
    tbar: [{
        text: '刷新',
        iconCls: 'refresh',
        handler: function() {
            EHSubmit.Work.Submit.ChooseForm.DataStore.load();
        }
    }],
    listeners: {
        render: function(thisGrid) {
            //----------请求单页数据-----------------
            thisGrid.store.load();
        },
        rowclick:function (thisGrid,rowIndex,e ){
			// ***主观题***
			//////显示当前选择的作业
			/*EHSubmit.showWin(EHSubmit.Work.Submit.SubmitWin);
			
			var form = Ext.getCmp('soSubmitForm');			
			var store = thisGrid.getStore();
            var rec = store.getAt(rowIndex);
			form.getForm().findField('goalId').setValue(rec.get('ID'));
			form.getForm().findField('goalTitle').setValue(rec.get('Title'));
			*/
			var store = thisGrid.getStore();
            var rec = store.getAt(rowIndex);
			
			// 当前选中的goalId，暂时用全局变量
			EHSubmit.Work.Submit.CurrentGoalId = rec.get('ID');
			EHSubmit.Work.Submit.CurrentGoalName = rec.get('Title');
			
			var goalType = rec.get('GoalType');
			switch(goalType){
				case 0:  // 主观题
					EHSubmit.showWin(EHSubmit.Work.Submit.SubmitWin);
					break;
				case 1:  // 客观题
					EHSubmit.showWin(EHSubmit.Work.Submit.ObjectiveItem.WinConfig);
					break;
			}
			
			
			
		},
        delay: 10 // Allow rows to be rendered.
    }

};
        
/////////////////////////////////////////////////////////////////////

//// 填写作业信息,文件等
EHSubmit.Work.Submit.SubmitForm = {
    xtype: 'form',
    id: 'soSubmitForm',
    //autoHeight:true,
    height: 330,
    fileUpload: true,    // 上传Form
    labelAlign: 'left',
    buttonAlign: 'center',
    bodyStyle: 'padding:15px;',
    border: false,
	padding:10,
	bodyStyle: 'background-color:#DFE8F6',
    labelWidth: 80,
    monitorValid: true,

    defaults: { anchor: '95%', allowBlank: false, msgTarget: 'side' },
    items: [
        /*{ // 作业信息
            xtype: 'textfield',
            //id: 'Submit_Cur_Title',
            name: 'goalTitle2',
			value: EHSubmit.Work.Submit.CurrentGoalName,
			blankText: '请在列表中选择一个作业',
            fieldLabel: '作业信息'
        },*/
        { // 文件上传
            xtype: 'fileuploadfield',
            //id: 'uploader',
            emptyText: '选择一个文件',
            fieldLabel: '文件',
            name: 'filePath',
            blankText: '请选择要上传的文件',
            buttonText: '浏览...'
            //            buttonCfg: {
            //                iconCls: 'upload-icon'
            //            }
        },
        { // 作业说明字段
            xtype: 'htmleditor',
            fieldLabel: '作业说明',
            emptyText: '这里填写作业说明',
            name: 'description',
            height: 150,
            enableAlignments: false,
            enableLists: false
            //value: 'test'
        }
    ],
    buttons: [{
        text: '上传',
        handler: function() {
            var frm = Ext.getCmp('soSubmitForm');
            if (frm.getForm().isValid()) { // 验证表单
                frm.getForm().submit({     // 提交
                    url: EHSubmit.ajaxRoot + 'UploadHandler.ashx',
                    waitTitle: '等待',
                    waitMsg: '正在上传，请稍后...',
					params:{
						Op:'addWork',
						goalId:EHSubmit.Work.Submit.CurrentGoalId,
						goalTitle:EHSubmit.Work.Submit.CurrentGoalName
					},
                    method: 'POST',
                    success: function(form, action) {
                        var successed = action.result.success;
                        if (successed) {
                            ///////////////  提交成功处理  ///////////////////
                            Ext.MessageBox.alert('提示', '提交成功！');
							// ......关闭win
							EHSubmit.closeWin(EHSubmit.Work.Submit.SubmitWin);
                            // 提交成功,把列表中对应的项删除
                            EHSubmit.Work.Submit.ChooseForm.DataStore.remove(EHSubmit.Work.Submit.ChooseForm.DataStore.getById(EHSubmit.Work.Submit.CurrentGoalId));
                            
                            // 清除表单内容
                            frm.getForm().reset();
                            //////////////////////////////////////////////////
                        }
                        else {
                            Ext.MessageBox.alert('失败', '信息：' + action.result.msg);
                        }
                    },
                    failure: function(form, action) {
                        var errmsg = action.result.msg;
                        Ext.MessageBox.alert('错误', errmsg);
                    }   // failure  
                });
            } /// if is Valid
        }
    }, {
        text: '取消',
        handler: function() {
            EHSubmit.closeWin(EHSubmit.Work.Submit.SubmitWin);
        }
}]

};

//// 提交主观作业窗体

EHSubmit.Work.Submit.SubmitWin ={
	id: 'SubmitWin',
	xtype: 'window',
	//plain: true,
	border: true,
	autoHeight:true,
	layout: 'fit',
	modal: true,
	title: '提交作业(主观题)',
	frame: true,
	layout:'form',
	items:[EHSubmit.Work.Submit.SubmitForm]	
}






//////////////////////////////////////////////////////////////////////
/// 内部容器窗口包含选择和上传
EHSubmit.Work.Submit.innerForm = {
    layout: 'fit',
	border: false,
    /*title: '提交作业',
    height: 400,
    frame: true,
    */
    defaults: { bodyStyle: 'padding:5px;', border: false },
    items: [EHSubmit.Work.Submit.ChooseForm.GridPanel]
}


//////////////////////////////////////////////////////////////////////
//-------包含上传窗口的容器--------------
EHSubmit.Work.Submit.Tab = {
    id:'submitForm',
    layout: 'form',
    frame: false,
    closable:true,
    title:'提交作业',
    bodyStyle: 'padding:5px;',
    border: false,
    items: [EHSubmit.Work.Submit.innerForm]
};
